<template>
	<view class="container">

		<view class="search-box">
			<u-search placeholder="搜索商户名称" v-model="searchKey" @search="handleSearch" @clear="handleSearch"></u-search>
		</view>

		<view class="list">
			<u-cell-group>
				<u-cell v-for="item in merchantList" :key="item.id" :title="item.name" isLink
					@click="handleMerchantDetail(item.id)">
					<template #value>
						<u-image :src="item.store_image" width="80rpx" height="80rpx" mode="aspectFill"></u-image>
					</template>
				</u-cell>
			</u-cell-group>

			<u-loadmore :status="loadStatus" :icon-type="iconType" :load-text="loadText" />
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from "vue";
	import {
		agentMerchant
	} from "@/common/apis/agent.js";
	import {
		useStore
	} from "vuex";

	const store = useStore();
	const merchantList = ref([]);
	const searchKey = ref("");
	const currentPage = ref(1);
	const totalPage = ref(1);
	const loadStatus = ref("loadmore");
	const iconType = ref("circle");
	const loadText = ref({
		loadmore: "上拉加载更多",
		loading: "正在加载...",
		nomore: "没有更多了",
	});

	async function fetchMerchantList() {
		loadStatus.value = "loading";

		try {
			const response = await agentMerchant({
				page: currentPage.value,
				keyword: searchKey.value,
			});

			if (currentPage.value === 1) {
				merchantList.value = response.records;
			} else {
				merchantList.value = [...merchantList.value, ...response.records];
			}

			totalPage.value = response.total_page;
			loadStatus.value =
				currentPage.value >= totalPage.value ? "nomore" : "loadmore";
		} catch (error) {
			console.error(error);
			loadStatus.value = "loadmore";
		}
	}

	function handleSearch() {
		currentPage.value = 1;
		fetchMerchantList();
	}

	function handleMerchantDetail(id) {
		uni.navigateTo({
			url: `/pages/agenter/merchant-detail?id=${id}`,
		});
	}

	onMounted(() => {
		fetchMerchantList();
	});
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;

		.search-box {
			margin: 20rpx 0;
			background: #fff;
			padding: 20rpx;
			border-radius: 16rpx;
		}

		.list {
			margin-top: 20rpx;
			background: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
		}
	}
</style>